package com.itlong.cloud.app.service.impl;

import com.itlong.cloud.POJO.DTO.property.IotCloudElevatorStateDTO;
import com.itlong.cloud.POJO.PO.CloudElevatorOperateRecordPO;
import com.itlong.cloud.POJO.PO.ColdDataCloudElevatorOperateRecordPO;
import com.itlong.cloud.POJO.VO.property.CloudElevatorVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.app.dao.IAppCloudElevatorCallStatusDao;
import com.itlong.cloud.app.dao.IAppDeviceDao;
import com.itlong.cloud.app.service.IAppCloudElevatorCallStatusService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      云电梯用户预约行程业务接口实现类
 * </desc>
 *
 * @createDate 2018/04/13
 */
@Service
public class AppCloudElevatorCallStatusServiceImpl implements IAppCloudElevatorCallStatusService{

    @Autowired
    IAppCloudElevatorCallStatusDao iAppCloudElevatorCallStatusDao;

    @Autowired
    IAppDeviceDao iAppDeviceDao;
    /**
     * <desc>
     *      检测用户预约中的行程，并更新用户预约行程状态
     * </desc>
     *
     * @param dto
     * @author Jiaqi.X
     * @createDate 2018/04/13
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void updateCallStatus(IotCloudElevatorStateDTO dto) {
        //通过当前电梯上传的真实楼层，查询电梯楼层标识
        CloudElevatorVO elevator = iAppDeviceDao.getElevatorNameAndProductKeyByDeviceUnique(dto.getDeviceName());
        //设置真实楼层为楼层标识
        dto.setFloor(StringUtils.isBlank(elevator.getVersion()) ||
                Integer.valueOf(elevator.getVersion().substring(elevator.getVersion().indexOf("V")+1, elevator.getVersion().indexOf("V")+5)) < 1040 ?
                iAppCloudElevatorCallStatusDao.findNaturalFloorByTruthFloor(dto) : iAppCloudElevatorCallStatusDao.findNaturalFloorByLogicFloor(dto));
        //查询电梯的群控器号
        Map<String,Object> controller = iAppDeviceDao.getControllerDeviceUniqueByElevatorDeviceUnique(dto.getDeviceName());
        if(controller != null && controller.get("groupConId") != null){
            dto.setGroupConId(controller.get("groupConId").toString());
            dto.setDeviceName(null);
        }
        //更新当前出发楼层号为电梯当前停靠楼层的行程，且是否已到出发楼层为否，预约状态为预约中，并修改是否已到出发楼层为是
        iAppCloudElevatorCallStatusDao.updateFromStatus(dto);
        //更新当前目标楼层号为电梯当前停靠楼层的行程，且是否已到出发楼层为是，是否已到目标楼层为否，预约状态为预约中，并修改是否已到目标楼层为是，预约状态为预约完成
        iAppCloudElevatorCallStatusDao.updateOperateStatus(dto);
    }

    /**
     * <desc>
     *      删除一天前的电梯状态
     * </desc>
     *
     * @return
     * @author Jiaqi.X
     * @createDate 2018/04/13
     */
    @Override
    public Integer deleteYestodayCallStatus() {
        return iAppCloudElevatorCallStatusDao.deleteYestodayCallStatus();
    }

    /**
     * <desc>
     *      将所有超过10分钟都没有预约完成的电梯状态修改为呼梯失败
     * </desc>
     *
     * @return
     * @author Jiaqi.X
     * @createDate 2018/04/13
     */
    @Override
    public Integer setCallStatusAsCallDefeat() {
        return iAppCloudElevatorCallStatusDao.setCallStatusAsCallDefeat();
    }


    /**
     * <desc>
     *      冷表数据转移
     * </desc>
     *
     * @author Jiaqi.X
     * @createDate 2020/04/13
     */
    @Override
    public void coldDataRemove() throws Exception {
        List<CloudElevatorOperateRecordPO> users = iAppCloudElevatorCallStatusDao.getUsers();
        for (CloudElevatorOperateRecordPO user : users) {
            String[] deviceUniques = StringUtils.isNotBlank(user.getDeviceUnique()) ? StringHandlerUtil.splitString(user.getDeviceUnique()) : new String[]{};
            for (String deviceUnique : deviceUniques) {
                Integer pageSize = 5000;  //页面大小
                boolean doFlag = true;
                while (doFlag) {
                    //此处休眠是为了避免主从库同步问题
                    Thread.sleep(2500);
                    List<ColdDataCloudElevatorOperateRecordPO> colds = iAppCloudElevatorCallStatusDao.getColds(user.getUserId(), deviceUnique, pageSize);
                    List<String> deletes = new ArrayList<>();
                    List<Map<String, Object>> batchs = new ArrayList<>();
                    if (colds.size() > 5) {
                        for (int i = colds.size() - 1; i >= 0; i--) {
                            if (i < 5) {
                                break;
                            } else {
                                batchs.add(SqlUtil.durableData(colds.get(i), PlatformConstants.TABLE_SAVE));
                                deletes.add(colds.get(i).getRecordId());
                            }
                        }
                    }
                    if (batchs.size() > 0) {
                        //保存冷数据
                        iAppCloudElevatorCallStatusDao.batchSaveColds(batchs);
                        //删除原数据
                        iAppCloudElevatorCallStatusDao.deleteColds(deletes);
                    }
                    //查询结果集小于页面大小就跳出循环
                    if (colds == null || colds.size() < pageSize) {
                        doFlag = false;
                    }
                }
            }
        }
    }
}
